package com.mediacloud.app.newsmodule.view

import android.content.Context
import android.graphics.Color
import android.graphics.Point
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.mediacloud.app.assembly.util.QRCodeUtil
import com.mediacloud.app.assembly.util.load
import com.mediacloud.app.assembly.util.otherLoad
import com.mediacloud.app.newsmodule.R
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.mediacloud.app.newsmodule.adaptor.comment.ShareCommentItem
import org.jetbrains.anko.centerInParent
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread

class PosterShareView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr)
{
    var posterDrawable:Drawable?=null

    var bgImage:ImageView?=null

    /**
     * 默认缩放比例 大于屏幕的时候就要等比缩小  小于屏幕剩余的宽高的时候 就原样显示就完求了
     */
    var scaleValue=1.0F

    fun showPosterView()
    {
        var commentPointItem:PointView?=null
        pointView?.forEach { item ->
            item.tlP.x = (scaleValue * item.tlP.x).toInt()
            item.tlP.y = (scaleValue * item.tlP.y).toInt()
            item.brP.x = (scaleValue * item.brP.x).toInt()
            item.brP.y = (scaleValue * item.brP.y).toInt()
            if(item.type==PointType.CommentContent)
            {
                commentPointItem=item
            }
        }

        commentPointItem?.let {item->
            val user_point_tl=Point(item.tlP.x,item.tlP.y)
            val user_point_br=Point(item.brP.x,item.tlP.y+context.resources.getDimensionPixelSize(R.dimen.dime_34))
            val comment_point_tl=Point(item.tlP.x,user_point_br.y)
            val comment_point_br=Point(item.brP.x,item.brP.y)
            val commentContent=PointView(comment_point_tl,comment_point_br,PointType.Content,(item.value as ShareCommentItem).comment)



            val userContent=PointView(user_point_tl,user_point_br,PointType.CommentUserInfo,item.value)

            pointView?.remove(item)
            pointView?.add(commentContent)
            pointView?.add(userContent)

        }

        pointView?.forEach { item->

            var w=item.brP.x-item.tlP.x
            var h=item.brP.y-item.tlP.y

            val lp=LayoutParams(w,h)

            when {
                item.type==PointType.Title || item.type==PointType.Content -> {
                    var textView=createTextView()
                    textView.setTag(R.id.recyclerItemData,item)
                    textView.text="${item.value}"
                    if(item.type==PointType.Title)
                    {
                        textView.gravity=Gravity.CENTER
                        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,context.resources.getDimension(R.dimen.sp_18))
                        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,context.resources.getDimension(R.dimen.sp_17))
                    }
                    else
                    {
                        textView.gravity = Gravity.CENTER_VERTICAL
                        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,context.resources.getDimension(R.dimen.sp_12))
                    }
                    textView.maxHeight=lp.height
                    this.addView(textView,lp)
                }
                item.type==PointType.Image -> {
                    var imageView=createImageView()
                    imageView.scaleType=ImageView.ScaleType.FIT_CENTER
                    imageView.setTag(R.id.recyclerItemData,item)
                    this.addView(imageView,lp)
                    imageView.load("${item.value}")
                }
                item.type==PointType.QrCode -> {
                    var imageView=createImageView()
                    imageView.setTag(R.id.recyclerItemData,item)
                    this.addView(imageView,lp)
                    doAsync {
                        var qrCode= QRCodeUtil.createQRImage("${item.value}",lp.width,lp.height,null)
                        uiThread {
                            imageView.setImageBitmap(qrCode)
                        }
                    }
                }
                item.type==PointType.CommentUserInfo -> {
                    var userView=LayoutInflater.from(context).inflate(R.layout.comment_shareposter_content,null)
                    var commentData=item.value as ShareCommentItem
                    var userHead:ImageView=userView.findViewById(R.id.userHead)
                    var nickName:TextView=userView.findViewById(R.id.nickName)
                    userHead.load(commentData.userIcon)
                   // GlideUtils.loadUrl(commentData.userIcon,userHead,null,null,false,true,null,true)
                    nickName.text=commentData.userName
                    userView.setTag(R.id.recyclerItemData,item)
                    addView(userView,lp)
                }
                //加载资源布局的
                item.type==PointType.ResLayoutId&&item.value!=null&& item.value is Int -> {
                    var view=LayoutInflater.from(context).inflate(item.value as Int,null)
                    view.setTag(R.id.recyclerItemData,item)
                    addView(view,lp)
                }
                //加载显示已经inflate好的布局
                item.type==PointType.LayoutView&&item.value!=null&& item.value is View -> {
                    var view=item.value as View
                    view.setTag(R.id.recyclerItemData,item)
                    addView(view,lp)
                }
            }
        }
    }

    var url:String?=null
    fun loadPosterImage(url:String="https://img.zcool.cn/community/01075c5a71ac12a80120a1235b8390.jpg@1280w_1l_2o_100sh.jpg")
    {
        removeAllViews()
        this.url=url
        otherLoad(context,url,object : RequestListener<Drawable?> {
            override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Drawable?>?, isFirstResource: Boolean): Boolean {
                return false
            }

            override fun onResourceReady(drawable: Drawable?, model: Any?, target: Target<Drawable?>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                if(drawable!=null)
                {
                    removeAllViews()
                    var originW=drawable.intrinsicWidth
                    var originH=drawable.intrinsicHeight
                    posterDrawable=drawable

                    var imageView=createImageView()
                    var lp=LayoutParams(-1,-1)
                    lp.centerInParent()
                    var parentView=(parent as ViewGroup)
                    var parentWidth=parentView.measuredWidth-parentView.paddingStart-parentView.paddingEnd
                    var parentHeight=parentView.measuredHeight-parentView.paddingTop-parentView.paddingBottom
                    if(originH>parentHeight&&originW>parentWidth)
                    {
                        scaleValue=1.0f*parentHeight/originH
                    }
                    else if(originH>parentHeight)
                    {
                        scaleValue=1.0f*parentHeight/originH
                    }
                    else if(originW>parentWidth)
                    {
                        scaleValue=1.0f*parentWidth/originW
                    }

                    lp.width= (originW*scaleValue).toInt()
                    lp.height= (originH*scaleValue).toInt()
                    imageView.setImageDrawable(drawable)
                    addView(imageView,lp)
                    bgImage=imageView
                    showPosterView()
                    setOnClickListener {  }
                }
                return false
            }
        })
    }

    var pointView:MutableList<PointView>?=null

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int)
    {
        super.onLayout(changed, l, t, r, b)
        if(visibility== View.GONE)
            return

        for( index in 0 until childCount)
        {
            var childView=getChildAt(index)
            var item:PointView?= childView.getTag(R.id.recyclerItemData) as PointView?
            if(childView.visibility!=View.GONE&&item!=null)
            {
                var l=(bgImage?.left?:0)+item.tlP.x
                var t=(bgImage?.top?:0)+item.tlP.y
                var r=(bgImage?.left?:0)+item.brP.x
                var b=(bgImage?.top?:0)+item.brP.y
                childView.layout(l,t,r,b)
                if(childView is TextView)
                {
                    var layout=childView.layout
                    for ( i in 0 until  childView.lineCount)
                    {
                        if( layout.getLineBottom(i)>=(b-t))
                        {
                            if(i>0)
                                childView.maxLines=i
                            else
                                childView.maxLines=1
                            break
                        }
                    }
                    Log.w("APPTAG","childView:$childView")
                }
            }
        }
    }

    fun createTextView():TextView
    {
        val textView=TextView(context)
        textView.setTextColor(Color.BLACK)
        textView.ellipsize=TextUtils.TruncateAt.END
        return textView
    }

    fun createImageView():ImageView
    {
        val imageView= ImageView(context)
        imageView.scaleType=ImageView.ScaleType.FIT_XY
        return imageView
    }

}

object  PointType
{
    const val Image=1
    const val Title=2
    const val QrCode=3
    const val Content=4
    const val CommentContent=5
    const val CommentUserInfo=6
    const val ResLayoutId=7
    const val LayoutView=8
}
class PointView(var tlP:Point,var brP:Point,var type:Int,var value:Any)
